package com.huatai.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huatai.common.util.StringUtil;
import com.huatai.user.constant.MinioBucket;
import com.huatai.user.entity.LogoManager;
import com.huatai.user.mapper.LogoManagerMapper;
import com.huatai.user.service.LogoManagerService;
import com.huatai.user.vo.LogoManagerVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class LogoManageServiceImpl extends ServiceImpl<LogoManagerMapper, LogoManager> implements LogoManagerService {

	@Value("${minio.PREURL}")
	private String minioUrl;

	@Override
	public boolean saveLogoManager(LogoManager logoManager) {
		//没传数据
		if (logoManager == null) {
			return false;
		}
		//是否新增
		if (logoManager.getId() != null) {
			return updateExistingLogo(logoManager);
		} else {
			return saveNewLogo(logoManager);
		}
	}


	/**
	 * 更新logoUrl
	 *
	 * @param logoManager
	 * @return
	 */
	private boolean updateExistingLogo(LogoManager logoManager) {
		LogoManager existingLogo = getById(logoManager.getId());
		if (existingLogo == null) {
			return false;
		}
		updateLogoDetails(existingLogo, logoManager);
		return updateById(existingLogo);
	}

	/**
	 * 新增logo配置
	 *
	 * @param logoManager
	 * @return
	 */
	private boolean saveNewLogo(LogoManager logoManager) {
		return save(logoManager);
	}

	/**
	 * 更新
	 *
	 * @param existingLogo
	 * @param newDetails
	 */
	private void updateLogoDetails(LogoManager existingLogo, LogoManager newDetails) {
		if (!StringUtil.isEmpty(newDetails.getLogoUrl())) {
			existingLogo.setLogoUrl(newDetails.getLogoUrl());
		}
		if (!StringUtil.isEmpty(newDetails.getIconUrl())) {
			existingLogo.setIconUrl(newDetails.getIconUrl());
		}
		if (!StringUtil.isEmpty(newDetails.getTitle())) {
			existingLogo.setTitle(newDetails.getTitle());
		}
	}

	@Override
	public LogoManagerVo selectLogoManagerList() {
		LogoManager logoManager = baseMapper.selectOne(new QueryWrapper<>());
		LogoManagerVo logoManagerVo = new LogoManagerVo();
		if (logoManager != null) {
			logoManager.setLogoUrl(minioUrl + "/" + MinioBucket.GH_MODEL_BUCKET_NAME_PRIVATE + "/" + logoManager.getLogoUrl());
			logoManager.setIconUrl(minioUrl + "/" + MinioBucket.GH_MODEL_BUCKET_NAME_PRIVATE + "/" + logoManager.getIconUrl());
		}else {
			return logoManagerVo;
		}
		BeanUtils.copyProperties(logoManager, logoManagerVo);
		return logoManagerVo;
	}

}

